/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.example;

import com.sun.star.beans.Property;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.XPropertySetInfo;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XNameAccess;
import com.sun.star.container.XNameContainer;
import com.sun.star.container.XNamed;
import com.sun.star.frame.XDesktop;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.IndexOutOfBoundsException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sdb.XBookmarksSupplier;
import com.sun.star.style.XStyle;
import com.sun.star.style.XStyleFamiliesSupplier;
import com.sun.star.text.ControlCharacter;
import com.sun.star.text.XParagraphCursor;
import com.sun.star.text.XText;
import com.sun.star.text.XTextContent;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextRange;
import com.sun.star.text.XTextTablesSupplier;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XRefreshable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Shameera
 */
public class CurrentDocument {
    private final XComponentContext m_xContext;
    private XMultiComponentFactory xmcf;
    private Object desktop;
    private XDesktop xDesktop;
    private XComponent xDoc;
    private XTextDocument textDocument;
    private XText text;
    private String ap;
    private XPropertySetInfo xpropInfo;

    public CurrentDocument(XComponentContext xComponentContext) throws Exception {
        this.m_xContext = xComponentContext;
        getCurrentTextDocument();
//        appendText("this is what the addon append to the content of the document");
//        getAllBookMark();
//        TextSectionExample();
//        getTables();
//        StylesExample();
        addcharactorStyle();

    }

    private void  getCurrentTextDocument() throws Exception{
        xmcf = m_xContext.getServiceManager();
        desktop = xmcf.createInstanceWithContext("com.sun.star.frame.Desktop", m_xContext);
        xDesktop = (XDesktop) UnoRuntime.queryInterface
                            (com.sun.star.frame.XDesktop.class, desktop);
        xDoc = xDesktop.getCurrentComponent();
        textDocument = (XTextDocument)UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class, xDoc);

    }

    private void appendText(String appendText){
        text = textDocument.getText();
        String content = text.getString();
        text.setString(content+" "+appendText);
    }

    private void getOdtName(){

    }

/** This method demonstrates how to create, insert and apply styles
  */
 protected void StylesExample() {
     try {
            XText mxDocText = textDocument.getText();
            XTextCursor mxDocCursor = mxDocText.createTextCursor();
         // Go to the end of the document
         mxDocCursor.gotoEnd(false);

//         // Insert two paragraph breaks
//         mxDocText.insertControlCharacter(
//             mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false);
//         mxDocText.insertControlCharacter(
//             mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false);

          com.sun.star.lang.XMultiServiceFactory mxDocFactory = (com.sun.star.lang.XMultiServiceFactory) UnoRuntime.queryInterface(
            com.sun.star.lang.XMultiServiceFactory.class, textDocument);
         // Create a new style from the document's factory
         XStyle xStyle = (XStyle) UnoRuntime.queryInterface(
             XStyle.class, mxDocFactory.createInstance("com.sun.star.style.ParagraphStyle"));

         // Access the XPropertySet interface of the new style
         XPropertySet xStyleProps = (XPropertySet) UnoRuntime.queryInterface(
             XPropertySet.class, xStyle);

         // Give the new style a light blue background
         xStyleProps.setPropertyValue ("ParaBackColor", new Integer(13421823));

         // Get the StyleFamiliesSupplier interface of the document
         XStyleFamiliesSupplier xSupplier = (XStyleFamiliesSupplier)UnoRuntime.queryInterface(
             XStyleFamiliesSupplier.class, textDocument);
         
         // Use the StyleFamiliesSupplier interface to get the XNameAccess interface of the
         // actual style families
         XNameAccess xFamilies = (XNameAccess) UnoRuntime.queryInterface (
             XNameAccess.class, xSupplier.getStyleFamilies());

         // Access the 'ParagraphStyles' Family
         XNameContainer xFamily = (XNameContainer) UnoRuntime.queryInterface(
             XNameContainer.class, xFamilies.getByName("ParagraphStyles"));

         // Insert the newly created style into the ParagraphStyles family
         xFamily.insertByName ("All-Singing All-Dancing Style", xStyle);

         // Get the XParagraphCursor interface of the document cursor
         XParagraphCursor xParaCursor = (XParagraphCursor) UnoRuntime.queryInterface(
             XParagraphCursor.class, mxDocCursor);

         // Select the first paragraph inserted
         xParaCursor.gotoPreviousParagraph(false);
         xParaCursor.gotoPreviousParagraph(true);

         // Access the property set of the cursor selection
         XPropertySet xCursorProps = (XPropertySet) UnoRuntime.queryInterface(
             XPropertySet.class, mxDocCursor);

         // Set the style of the cursor selection to our newly created style
         xCursorProps.setPropertyValue("ParaStyleName", "All-Singing All-Dancing Style");

         // Go back to the end
         mxDocCursor.gotoEnd(false);

         // Select the last paragraph in the document
         xParaCursor.gotoNextParagraph(true);

         // And reset it's style to 'Standard' (the programmatic name for the default style)
         xCursorProps.setPropertyValue("ParaStyleName", "Standard");

     } catch (Exception e) {
         e.printStackTrace (System.out);
     }
 }

 private void addcharactorStyle(){
        try {
                        XText mxDocText = textDocument.getText();
            XTextCursor mxDocCursor = mxDocText.createTextCursor();
         // Go to the end of the document
         mxDocCursor.gotoEnd(false);
            com.sun.star.lang.XMultiServiceFactory mxDocFactory = (com.sun.star.lang.XMultiServiceFactory) UnoRuntime.queryInterface(
            com.sun.star.lang.XMultiServiceFactory.class, textDocument);
            XStyle xStyle = (XStyle) UnoRuntime.queryInterface(
             XStyle.class, mxDocFactory.createInstance("com.sun.star.style.CharacterStyle"));
             XPropertySet xStyleProps = (XPropertySet) UnoRuntime.queryInterface(
             XPropertySet.class, xStyle);
              xStyleProps.setPropertyValue ("CharColor", new Integer(0xC81FB9));
              XStyleFamiliesSupplier xSupplier = (XStyleFamiliesSupplier)UnoRuntime.queryInterface(
             XStyleFamiliesSupplier.class, textDocument);
              XNameAccess xFamilies = (XNameAccess) UnoRuntime.queryInterface (
             XNameAccess.class, xSupplier.getStyleFamilies());
                       XNameContainer xFamily = (XNameContainer) UnoRuntime.queryInterface(
             XNameContainer.class, xFamilies.getByName("CharacterStyles"));
                       xFamily.insertByName ("@Colour", xStyle);
                                // Access the property set of the cursor selection
         XPropertySet xCursorProps = (XPropertySet) UnoRuntime.queryInterface(
             XPropertySet.class, mxDocCursor);

         // Set the style of the cursor selection to our newly created style
         xCursorProps.setPropertyValue("CharStyleName", "@Colour");
         mxDocCursor.gotoEnd(false);
         mxDocText.setString("this is should be in different colour");
         //mxDocCursor.gotoEnd(false);
                  // And reset it's style to 'Standard' (the programmatic name for the default style)
         
         mxDocText.setString("this is should be default colour");
         xCursorProps.setPropertyValue("CharStyleName", "Default");
         
        } catch (Exception ex) {
            ex.printStackTrace (System.out);
        }
 }

    private void getAllBookMark() {
        try {
            // Create a new cell range container
            com.sun.star.lang.XMultiServiceFactory xDocFactory = (com.sun.star.lang.XMultiServiceFactory) UnoRuntime.queryInterface(
            com.sun.star.lang.XMultiServiceFactory.class, textDocument);
            // inserting and retrieving a bookmark
            Object bookmark = xDocFactory.createInstance("com.sun.star.text.Bookmark");
            // name the bookmark
            XNamed xNamed = (XNamed) UnoRuntime.queryInterface (
     XNamed.class, bookmark );
            xNamed.setName("MyUniqueBookmarkName");
            // get XTextContent interface
            XTextContent xTextContent = (XTextContent) UnoRuntime.queryInterface (
     XTextContent.class, bookmark );
//            XTextRange textRange = xTextContent.getAnchor();
            XText xDocText = textDocument.getText();
             // insert bookmark at the end of the document
             // instead of mxDocText.getEnd you could use a text cursor's XTextRange interface or any XTextRange
             xDocText.insertTextContent ( xDocText.getEnd(), xTextContent, false );
//             query XBookmarksSupplier from document model and get bookmarks collection
            XBookmarksSupplier xBookmarksSupplier = (XBookmarksSupplier) UnoRuntime.queryInterface(
                XBookmarksSupplier.class, xDoc);
            XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks();
            if (xNamedBookmarks != null) {
                String[] bookMarks = xNamedBookmarks.getElementNames();
                System.out.println("inside the getAllBookMark method");
                for (String aBookmark : bookMarks) {
                    System.out.println(bookmark);
                }
            } else {
                System.out.println("xNameBookMarks is null");
            }
        } catch (Exception ex) {
            Logger.getLogger(CurrentDocument.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

     /** This method demonstrates how to create linked and unlinked sections
  */
 protected void TextSectionExample() {
     try {
                     com.sun.star.lang.XMultiServiceFactory mxDocFactory = (com.sun.star.lang.XMultiServiceFactory) UnoRuntime.queryInterface(
            com.sun.star.lang.XMultiServiceFactory.class, textDocument);
            XText mxDocText = textDocument.getText();
            XTextCursor mxDocCursor = mxDocText .createTextCursor();
         // Go to the end of the document
         mxDocCursor.gotoEnd(false);
         // Insert two paragraph breaks
         mxDocText.insertControlCharacter(
             mxDocCursor, ControlCharacter.HARD_HYPHEN, false);
         mxDocText.insertControlCharacter(
             mxDocCursor, ControlCharacter.HARD_HYPHEN, true);

         // Create a new TextSection from the document factory and access it's XNamed interface
         XNamed xChildNamed = (XNamed) UnoRuntime.queryInterface(
           XNamed.class, mxDocFactory.createInstance("com.sun.star.text.TextSection"));
         // Set the new sections name to 'Child_Section'
         xChildNamed.setName("Child_Section");

         // Access the Child_Section's XTextContent interface and insert it into the document
         XTextContent xChildSection = (XTextContent) UnoRuntime.queryInterface(
             XTextContent.class, xChildNamed);
         mxDocText.insertTextContent (mxDocCursor, xChildSection, false);

         // Access the XParagraphCursor interface of our text cursor
         XParagraphCursor xParaCursor = (XParagraphCursor) UnoRuntime.queryInterface(
             XParagraphCursor.class, mxDocCursor);

         // Go back one paragraph (into Child_Section)
         xParaCursor.gotoPreviousParagraph(false);

         // Insert a string into the Child_Section
         mxDocText.insertString(mxDocCursor, "This is a test", false);

         // Go to the end of the document
         mxDocCursor.gotoEnd(false);

         // Go back two paragraphs
         xParaCursor.gotoPreviousParagraph (false);
         xParaCursor.gotoPreviousParagraph (false);
         // Go to the end of the document, selecting the two paragraphs
         mxDocCursor.gotoEnd(true);

         // Create another text section and access it's XNamed interface
         XNamed xParentNamed = (XNamed) UnoRuntime.queryInterface(XNamed.class,
             mxDocFactory.createInstance("com.sun.star.text.TextSection"));

         // Set this text section's name to Parent_Section
         xParentNamed.setName ("Parent_Section");

         // Access the Parent_Section's XTextContent interface ...
         XTextContent xParentSection = (XTextContent) UnoRuntime.queryInterface(
             XTextContent.class, xParentNamed);
         // ...and insert it into the document
         mxDocText.insertTextContent(mxDocCursor, xParentSection, false);

         // Go to the end of the document
         mxDocCursor.gotoEnd (false);
         // Insert a new paragraph
         mxDocText.insertControlCharacter(
             mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false);
         // And select the new pargraph
         xParaCursor.gotoPreviousParagraph(true);

         // Create a new Text Section and access it's XNamed interface
         XNamed xLinkNamed = (XNamed) UnoRuntime.queryInterface(
             XNamed.class, mxDocFactory.createInstance("com.sun.star.text.TextSection"));
         // Set the new text section's name to Linked_Section
         xLinkNamed.setName("Linked_Section");

         // Access the Linked_Section's XTextContent interface
         XTextContent xLinkedSection = (XTextContent) UnoRuntime.queryInterface(
             XTextContent.class, xLinkNamed);
         // And insert the Linked_Section into the document
         mxDocText.insertTextContent(mxDocCursor, xLinkedSection, false);

         // Access the Linked_Section's XPropertySet interface
         XPropertySet xLinkProps = (XPropertySet) UnoRuntime.queryInterface(
             XPropertySet.class, xLinkNamed);
         // Set the linked section to be linked to the Child_Section
         xLinkProps.setPropertyValue("LinkRegion", "Child_Section");

         // Access the XPropertySet interface of the Child_Section
         XPropertySet xChildProps = (XPropertySet) UnoRuntime.queryInterface(
             XPropertySet.class, xChildNamed);
         // Set the Child_Section's background colour to blue
         xChildProps.setPropertyValue("BackColor", new Integer(11111111));

         // Refresh the document, so the linked section matches the Child_Section
         XRefreshable xRefresh = (XRefreshable) UnoRuntime.queryInterface(
             XRefreshable.class, textDocument);
         xRefresh.refresh();
     } catch (Exception e) {
         e.printStackTrace (System.out);
     }
 }

 private void getTables(){
      XTextTablesSupplier xTablesSupplier = (XTextTablesSupplier) UnoRuntime.queryInterface(
     XTextTablesSupplier.class, textDocument );
 // get the tables collection
 XNameAccess xNamedTables = xTablesSupplier.getTextTables();

 // now query the XIndexAccess from the tables collection
 XIndexAccess xIndexedTables = (XIndexAccess) UnoRuntime.queryInterface(
     XIndexAccess.class, xNamedTables);

 // we need properties
 XPropertySet xTableProps = null;
        Property[] propSet;

 // get the tables
 for (int i = 0; i < xIndexedTables.getCount(); i++) {
            try {
                Object table = xIndexedTables.getByIndex(i);
                // the properties, please!
                xTableProps = (XPropertySet) UnoRuntime.queryInterface(
         XPropertySet.class, table);
                // color the table light green in format 0xRRGGBB
                xTableProps.setPropertyValue("BackColor", new Integer(0xC8FFB9));
                xpropInfo = xTableProps.getPropertySetInfo();
                propSet = xpropInfo.getProperties();
                System.out.println("***************************************************");
//                for(Property prop : propSet){
//                    System.out.println(prop.Name);
//                }
                System.out.println(propSet.toString());
            } catch (UnknownPropertyException ex) {
                Logger.getLogger(CurrentDocument.class.getName()).log(Level.SEVERE, null, ex);
            } catch (PropertyVetoException ex) {
                Logger.getLogger(CurrentDocument.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(CurrentDocument.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IndexOutOfBoundsException ex) {
                Logger.getLogger(CurrentDocument.class.getName()).log(Level.SEVERE, null, ex);
            } catch (WrappedTargetException ex) {
                Logger.getLogger(CurrentDocument.class.getName()).log(Level.SEVERE, null, ex);
            }
 }
 }

}
